// CSS 格式化工具
class CSSFormatter {
    // CSS 关键字
    static cssKeywords = [
        // 伪类
        ':hover', ':active', ':focus', ':visited', ':link', ':first-child', ':last-child',
        ':nth-child', ':nth-of-type', ':before', ':after', ':not',
        // 属性
        'color', 'background', 'font', 'margin', 'padding', 'border', 'width', 'height',
        'display', 'position', 'float', 'clear', 'overflow', 'z-index', 'opacity',
        'transform', 'transition', 'animation', 'flex', 'grid'
    ];

    // 格式化CSS
    static formatCSS(css, options = {}) {
        try {
            if (!css || typeof css !== 'string') {
                return { success: false, error: 'CSS内容不能为空' };
            }

            const {
                indentSize = 2,
                indentType = 'space', // 'space' or 'tab'
                insertFinalNewline = true,
                trimTrailingWhitespace = true,
                preserveNewlines = true,
                maxPreserveNewlines = 2,
                bracesOnSameLine = false,
                addSemicolon = true
            } = options;

            // 基础清理
            let formatted = css.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
            
            // 移除注释（保留重要注释）
            formatted = this.preserveImportantComments(formatted);
            
            // 格式化CSS规则
            formatted = this.formatCSSRules(formatted, {
                indentSize,
                indentType,
                bracesOnSameLine,
                addSemicolon
            });
            
            // 处理换行
            if (!preserveNewlines || maxPreserveNewlines < 2) {
                formatted = formatted.replace(/\n{3,}/g, '\n\n');
            } else {
                const maxNewlines = '\n'.repeat(maxPreserveNewlines + 1);
                const regex = new RegExp(`\\n{${maxPreserveNewlines + 2},}`, 'g');
                formatted = formatted.replace(regex, maxNewlines);
            }
            
            // 移除尾随空白
            if (trimTrailingWhitespace) {
                formatted = formatted.replace(/[ \t]+$/gm, '');
            }
            
            // 添加最终换行符
            if (insertFinalNewline && !formatted.endsWith('\n')) {
                formatted += '\n';
            }
            
            return {
                success: true,
                data: {
                    formatted: formatted,
                    original: css,
                    stats: this.getCSSStats(css, formatted)
                }
            };
        } catch (error) {
            return { success: false, error: `CSS格式化失败: ${error.message}` };
        }
    }

    // 压缩CSS
    static minifyCSS(css, options = {}) {
        try {
            if (!css || typeof css !== 'string') {
                return { success: false, error: 'CSS内容不能为空' };
            }

            const { preserveImportant = true, removeComments = true } = options;

            let minified = css;
            
            // 移除注释（保留重要注释）
            if (removeComments) {
                if (preserveImportant) {
                    minified = this.removeNonImportantComments(minified);
                } else {
                    minified = minified.replace(/\/\*[\s\S]*?\*\//g, '');
                }
            }
            
            // 移除不必要的空白
            minified = minified
                .replace(/\s+/g, ' ') // 多个空白字符替换为单个空格
                .replace(/;\s*}/g, '}') // 移除分号前的空格和最后一个分号
                .replace(/\s*{\s*/g, '{') // 移除大括号周围的空格
                .replace(/}\s*/g, '}') // 移除右大括号后的空格
                .replace(/;\s*/g, ';') // 移除分号后的空格
                .replace(/:\s*/g, ':') // 移除冒号后的空格
                .replace(/,\s*/g, ',') // 移除逗号后的空格
                .replace(/\s*>\s*/g, '>') // 移除选择器符号周围的空格
                .replace(/\s*\+\s*/g, '+')
                .replace(/\s*~\s*/g, '~')
                .replace(/\s*\|\s*/g, '|');
            
            // 移除开头和结尾的空白
            minified = minified.trim();
            
            return {
                success: true,
                data: {
                    minified: minified,
                    original: css,
                    stats: this.getCSSStats(css, minified)
                }
            };
        } catch (error) {
            return { success: false, error: `CSS压缩失败: ${error.message}` };
        }
    }

    // 验证CSS语法
    static validateCSS(css) {
        try {
            if (!css || typeof css !== 'string') {
                return { success: false, error: 'CSS内容不能为空' };
            }

            const errors = [];
            const warnings = [];
            
            // 基础语法检查
            const lines = css.split('\n');
            let braceStack = [];
            let inComment = false;
            
            lines.forEach((line, index) => {
                const lineNum = index + 1;
                let cleanLine = line.trim();
                
                // 处理注释
                if (cleanLine.includes('/*')) {
                    inComment = true;
                }
                if (cleanLine.includes('*/')) {
                    inComment = false;
                    return;
                }
                if (inComment) return;
                
                // 检查大括号匹配
                const openBraces = (cleanLine.match(/{/g) || []).length;
                const closeBraces = (cleanLine.match(/}/g) || []).length;
                
                for (let i = 0; i < openBraces; i++) {
                    braceStack.push(lineNum);
                }
                
                for (let i = 0; i < closeBraces; i++) {
                    if (braceStack.length === 0) {
                        errors.push({
                            line: lineNum,
                            message: '多余的右大括号',
                            type: 'syntax'
                        });
                    } else {
                        braceStack.pop();
                    }
                }
                
                // 检查属性语法
                if (cleanLine.includes(':') && !cleanLine.includes('{') && !cleanLine.includes('}')) {
                    if (!cleanLine.endsWith(';') && !cleanLine.endsWith('{')) {
                        warnings.push({
                            line: lineNum,
                            message: '属性声明建议以分号结尾',
                            type: 'style'
                        });
                    }
                }
                
                // 检查选择器
                if (cleanLine.endsWith('{')) {
                    const selector = cleanLine.slice(0, -1).trim();
                    if (!selector) {
                        errors.push({
                            line: lineNum,
                            message: '空的选择器',
                            type: 'syntax'
                        });
                    }
                }
            });
            
            // 检查未闭合的大括号
            if (braceStack.length > 0) {
                braceStack.forEach(lineNum => {
                    errors.push({
                        line: lineNum,
                        message: '大括号未闭合',
                        type: 'syntax'
                    });
                });
            }
            
            const isValid = errors.length === 0;
            
            return {
                success: true,
                data: {
                    isValid,
                    errors,
                    warnings,
                    summary: `发现 ${errors.length} 个错误，${warnings.length} 个警告`
                }
            };
        } catch (error) {
            return { success: false, error: `CSS验证失败: ${error.message}` };
        }
    }

    // 格式化CSS规则
    static formatCSSRules(css, options) {
        const { indentSize, indentType, bracesOnSameLine, addSemicolon } = options;
        const indent = indentType === 'tab' ? '\t' : ' '.repeat(indentSize);
        
        let formatted = css;
        
        // 处理选择器和大括号
        formatted = formatted.replace(/([^{}]*?)\s*{\s*/g, (match, selector) => {
            const cleanSelector = selector.trim();
            if (bracesOnSameLine) {
                return `${cleanSelector} {\n`;
            } else {
                return `${cleanSelector}\n{\n`;
            }
        });
        
        // 处理属性声明
        formatted = formatted.replace(/([^{}]*?)}/g, (match, content) => {
            if (!content.trim()) return '}';
            
            const properties = content.split(';').filter(prop => prop.trim());
            const formattedProps = properties.map(prop => {
                const trimmed = prop.trim();
                if (trimmed) {
                    return `${indent}${trimmed}${addSemicolon && !trimmed.endsWith(';') ? ';' : ''}`;
                }
                return '';
            }).filter(prop => prop);
            
            return formattedProps.join('\n') + '\n}';
        });
        
        // 添加规则间的空行
        formatted = formatted.replace(/}\s*([.#@a-zA-Z])/g, '}\n\n$1');
        
        return formatted;
    }

    // 保留重要注释
    static preserveImportantComments(css) {
        return css.replace(/\/\*[\s\S]*?\*\//g, (comment) => {
            if (comment.includes('!') || comment.toLowerCase().includes('important')) {
                return comment;
            }
            return '';
        });
    }

    // 移除非重要注释
    static removeNonImportantComments(css) {
        return css.replace(/\/\*[\s\S]*?\*\//g, (comment) => {
            if (comment.includes('!') || comment.toLowerCase().includes('important')) {
                return comment;
            }
            return '';
        });
    }

    // 获取CSS统计信息
    static getCSSStats(original, processed) {
        const originalSize = original.length;
        const processedSize = processed.length;
        const savings = originalSize - processedSize;
        const savingsPercentage = originalSize > 0 ? (savings / originalSize * 100) : 0;
        
        // 统计规则数量
        const originalRules = (original.match(/{[^}]*}/g) || []).length;
        const processedRules = (processed.match(/{[^}]*}/g) || []).length;
        
        // 统计选择器数量
        const originalSelectors = (original.match(/[^{}]+(?=\s*{)/g) || []).length;
        const processedSelectors = (processed.match(/[^{}]+(?=\s*{)/g) || []).length;
        
        // 统计属性数量
        const originalProps = (original.match(/[^{}]+:[^{}]+(?=;|})/g) || []).length;
        const processedProps = (processed.match(/[^{}]+:[^{}]+(?=;|})/g) || []).length;
        
        return {
            originalSize,
            processedSize,
            savings,
            savingsPercentage: Math.round(savingsPercentage * 100) / 100,
            originalRules,
            processedRules,
            originalSelectors,
            processedSelectors,
            originalProps,
            processedProps
        };
    }

    // 美化CSS（添加语法高亮信息）
    static beautifyCSS(css) {
        try {
            if (!css || typeof css !== 'string') {
                return { success: false, error: 'CSS内容不能为空' };
            }

            // 格式化CSS
            const formatResult = this.formatCSS(css);
            if (!formatResult.success) {
                return formatResult;
            }

            const formatted = formatResult.data.formatted;
            
            // 添加语法高亮标记
            let highlighted = formatted
                // 选择器
                .replace(/([^{}]+)(?=\s*{)/g, '<span class="css-selector">$1</span>')
                // 属性名
                .replace(/(\s+)([a-zA-Z-]+)(\s*):/g, '$1<span class="css-property">$2</span>$3:')
                // 属性值
                .replace(/:(\s*)([^;{}]+)(;?)/g, ':<span class="css-value">$2</span>$3')
                // 重要声明
                .replace(/!important/g, '<span class="css-important">!important</span>')
                // 注释
                .replace(/(\/\*[\s\S]*?\*\/)/g, '<span class="css-comment">$1</span>');
            
            return {
                success: true,
                data: {
                    formatted: formatted,
                    highlighted: highlighted,
                    stats: formatResult.data.stats
                }
            };
        } catch (error) {
            return { success: false, error: `CSS美化失败: ${error.message}` };
        }
    }

    // 自动修复常见CSS问题
    static autoFixCSS(css) {
        try {
            if (!css || typeof css !== 'string') {
                return { success: false, error: 'CSS内容不能为空' };
            }

            let fixed = css;
            const fixes = [];
            
            // 添加缺失的分号
            const missingSemicolons = fixed.match(/[^;{}]\s*}/g);
            if (missingSemicolons) {
                fixed = fixed.replace(/([^;{}])\s*}/g, '$1;}');
                fixes.push(`添加了 ${missingSemicolons.length} 个缺失的分号`);
            }
            
            // 修复颜色值格式
            const colorFixes = fixed.match(/#[0-9a-fA-F]{3}(?![0-9a-fA-F])/g);
            if (colorFixes) {
                fixed = fixed.replace(/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])(?![0-9a-fA-F])/g, '#$1$1$2$2$3$3');
                fixes.push(`转换了 ${colorFixes.length} 个3位颜色值为6位格式`);
            }
            
            // 移除重复的属性（保留最后一个）
            fixed = fixed.replace(/([^{}]*{[^{}]*?)(\b\w+\s*:\s*[^;]+;)([^{}]*?)(\b\w+\s*:\s*[^;]+;)([^{}]*})/g, 
                (match, before, prop1, middle, prop2, after) => {
                    const propName1 = prop1.split(':')[0].trim();
                    const propName2 = prop2.split(':')[0].trim();
                    if (propName1 === propName2) {
                        fixes.push(`移除了重复的属性: ${propName1}`);
                        return before + middle + prop2 + after;
                    }
                    return match;
                });
            
            // 格式化结果
            const formatResult = this.formatCSS(fixed);
            if (!formatResult.success) {
                return formatResult;
            }
            
            return {
                success: true,
                data: {
                    fixed: formatResult.data.formatted,
                    original: css,
                    fixes: fixes,
                    stats: formatResult.data.stats
                }
            };
        } catch (error) {
            return { success: false, error: `CSS自动修复失败: ${error.message}` };
        }
    }
}